const puppeteer = require('puppeteer');
// let request = require('request-promise-native');
const moment = require('moment');
const nodeSchedule = require("node-schedule");
const superagent = require("superagent");
const user = {
    name: '账户名',
    password: '密码'
}

const fs = require('fs');
let options = {
    flags: 'a', //
    encoding: 'utf8', // utf8编码
}

let url = '内网登录页面';
let testUrl = 'https://www.baidu.com/';

//使用 puppeteer.launch 启动 Chrome
async function startConnect(logger) {
    logger.log(new Date().toLocaleString() + ' : network_connect start');
    try {
        const browser = await puppeteer.launch({
            headless: false,   //有浏览器界面启动
            // slowMo: 100,       //放慢浏览器执行速度，方便测试观察
            args: [            //启动 Chrome 的参数，详见上文中的介绍
                // '–no-sandbox',
                // '--window-size=1280,960'
                '--single-process',
                '- -no-zygote',
                '--no-sandbox'
            ],
        });
        logger.log(new Date().toLocaleString() + ' :launch');
        const page = await browser.newPage();
        await page.goto(url, {
            timeout: 10 * 1000,
            waitUntil: [
                'load',              //等待 “load” 事件触发
                'domcontentloaded',  //等待 “domcontentloaded” 事件触发
            ]
        });
        logger.log(new Date().toLocaleString() + ' :open page');
        // await page.screenshot({
        //     path: './screenshot/go-' + moment().format('yyyy-MM-DD-HH-mm-ss') + '.png',  //图片保存路径
        //     type: 'png',
        //     fullPage: true //边滚动边截图
        //     // clip: {x: 0, y: 0, width: 1920, height: 800}
        // });
        const uniqueIdElement = await page.$('#usr');
        await uniqueIdElement.type(user.name, {delay: 200});
        const passwordElement = await page.$('#pwd');
        await passwordElement.type(user.password, {delay: 200});
        //点击确定按钮进行登录
        let okButtonElement = await page.$('.subbtn');
        // 等待页面跳转完成，一般点击某个按钮需要跳转时，都需要等待 page.waitForNavigation() 执行完毕才表示跳转成功
        await Promise.all([
            okButtonElement.click(),
            page.waitForNavigation()
        ]);
        await page.screenshot({
            path: './screenshot/' + moment().format('yyyy-MM-DD-HH-mm-ss') + '.png',  //图片保存路径
            type: 'png',
            fullPage: true //边滚动边截图
            // clip: {x: 0, y: 0, width: 1920, height: 800}
        });
        await logger.log(new Date().toLocaleString() + ' : network_connect end');
        await page.close();
        await browser.disconnect();
        await browser.close();
    } catch (e) {
        await logger.log(new Date().toLocaleString() + ' err: ' + JSON.stringify(e));
        startConnect(logger)
    }
}

// startConnect()


// 秒、分、时、日、月、周几
//0,10,20,30,40,50
//22,23,0,1,2,3,4
nodeSchedule.scheduleJob('0 0,3,20,40,43,44,45,50 * * * *', async function () {
    try {
        var stderr = fs.createWriteStream('./log/' + new Date().toLocaleDateString() + '.log', options);
        // 创建logger
        var logger = new console.Console(stderr);
        superagent.get(testUrl, function (err, res) {
            if (err) {
                logger.log(new Date().toLocaleString() + ' : network_err ');
                startConnect(logger)
            } else {
                logger.log(new Date().toLocaleString() + ' : network_fine\n')
            }
        }).redirects(1)
    } catch (error) {
        console.error(error);
    }
});



//将node程序作为服务安装到windows服务，并设置开机自动启动
//nssm install auto_network "C:\Program Files\nodejs\node.exe" "D:\code\node_pc\auto_network\auto_network.js" net start auto_network
